import {
	uNavigateTo,
	umodal,
	utoast,
	uShowLoading,
	uHideLoading,
	uSetNavigationBarTitle,
	uNavigateBack,
} from "../utils/uniUtils.js";
import checker from "../common/graceChecker";
import {
	transfer
} from "../common/dataTransfer.js";
import {
	modeEnum
} from "../constants/normalConstants.js";
import {
	toastIconEnum
} from "../constants/uiConstants.js";
import {
	liValidateData
} from "../utils/liValidator";
import {
	batchJsonParse,
	batchJsonStringify
} from "../utils/liJsonUtils.js";
export default {
	methods: {
		loadEvent(options, context) {
			context.mode = options.mode == "edit" ? "edit" : "add";
			uSetNavigationBarTitle(
				(options.mode == "edit" ? "编辑" : "新增") + context.subject
			);

			if (context.mode == modeEnum.edit) {
				context.id = options.id;
			}
		},

		async mountedEvent(context, formData) {
			try {
				uShowLoading();
				if (context.mode == modeEnum.edit) {
					await context.getData();
				} else {
					context.form = formData;
				}
				context.getOtherData();
				context.isLoaded = true;
			} catch (error) {
				console.log("error", error);
				utoast("初始化失败~", toastIconEnum.error);
				setTimeout(() => {
					uNavigateBack();
				}, 800);
			} finally {
				uHideLoading();
			}
		},

		async getData() {
			const {
				data
			} = await this.getFn(this.id);
			this.form = data?.model || data;
			this.form =
				this.jsonProp && Array.isArray(this.jsonProp) ?
				batchJsonParse(this.form, this.jsonProp) :
				this.form;
		},

		async insertData() {
			return await this.addFn(this.form);
		},

		async delData() {
			return await this.delFn(this.id);
		},

		async editData() {
			return await this.editFn(this.form);
		},

		async btnDelClick() {
			const res = await umodal();
			if (res) {
				const result = await this.delData();
				console.log(result);
				if (result.code != null && result.code == 0) {
					await utoast("删除成功！", toastIconEnum.success);
					setTimeout(() => {
						uNavigateTo(`/pages/${this.rootRoute}/${this.routeName}/list`);
					}, 1000);
				} else {
					await utoast("删除失败！", toastIconEnum.error);
				}
			}
		},

		async formDelete(context) {
			const res = await umodal();
			if (res) {
				const result = await context.delData();
				console.log(result);
				if (result.code != null && result.code == 0) {
					await utoast("删除成功！", toastIconEnum.success);
					setTimeout(() => {
						uNavigateTo(
							`/pages/${context.rootRoute}/${context.routeName}/list`
						);
					}, 1000);
				} else {
					await utoast("删除失败！", toastIconEnum.error);
				}
			}
		},

		async formInsertOrEdit(context) {
			// console.log(context);
			context.form = transfer(context.form, context.transferRules);
			if (!Array.isArray(context.rules)) {
				try {
					await liValidateData(context.rules, context.form);
				} catch (error) {
					await utoast(error, toastIconEnum.none);
					return;
				}
			} else if (!checker.check(context.form, context.rules)) {
				await utoast(checker.error, toastIconEnum.none);
				return;
			}
			if (context.lock) {
				return;
			}

			if (!(await umodal("确认要提交吗？"))) {
				return;
			}

			const submitForm =
				context.jsonProp && Array.isArray(context.jsonProp) ?
				batchJsonStringify(context.form, context.jsonProp) :
				context.form;
			const res =
				context.mode == modeEnum.edit ?
				await context.editData(submitForm) :
				await context.insertData(submitForm);
			if (res?.code == 0) {
				await utoast("操作成功");
				setTimeout(() => {
					uni.reLaunch({
						url: `/pages/${context.rootRoute}/${context.routeName}/list`
					});
				}, 1000);
			} else {
				setTimeout(() => {
					context.lock = false;
				}, 2000);
			}
		},

		async formBlur(event, context) {
			const name = event.currentTarget.id;
			transfer(context.form, context.transferRules);

			if (name != null) {
				if (!Array.isArray(context.rules)) {
					try {
						const newObject = {};
						if (context.rules.hasOwnProperty(name)) {
							newObject[name] = context.rules[name];
						}

						await liValidateData(newObject, context.form);
					} catch (error) {
						await utoast(error, toastIconEnum.none);
						return;
					}
				} else {
					let rules = [];
					const rule = context.rules.find((item) => item.name == name);
					if (rule != null) {
						rules.push(rule);
						const isOk = checker.check(context.form, rules);

						if (!isOk) {
							utoast(checker.error, toastIconEnum.none);
							return;
						}
					}
				}
			}
		},

		async batchGetData(fnArr) {
			const promises = fnArr.map(async (element) => {
				const {
					data
				} = element.params ?
					await element.fn(element.params) :
					await element.fn();
				return {
					name: element.name,
					data
				};
			});

			try {
				const results = await Promise.all(promises);
				results.forEach(({
					name,
					data
				}) => {
					if (data?.list) {
						this[name] = data.list;
					} else {
						this[name] = data;
					}
				});
			} catch (error) {
				console.error("error-->", error);
			}
		},

		async batchReqData(fnArr) {
			const promises = fnArr.map(async (element) => {
				const {
					data
				} = element.params ?
					await element.fn(element.params) :
					await element.fn();
				return {
					name: element.name,
					data
				};
			});

			try {
				const results = await Promise.all(promises);
				let obj = {};
				results.forEach(({
					name,
					data
				}) => {
					if (data?.list) {
						obj[name] = data.list;
					} else {
						obj[name] = data;
					}
				});
			} catch (error) {
				console.error("error-->", error);
			}
			return obj;
		},

		// methods put on the top
	},
};